<!DOCTYPE html>
<html>
<head>
<title>Hello WebSocket</title>
<script src="http://cdn.bootcss.com/jquery/3.1.0/jquery.min.js"></script>
<script src="/js/stomp.min.js"></script>
<script src="http://cdn.bootcss.com/sockjs-client/1.1.1/sockjs.min.js"></script>
<script type="text/javascript">
	$(document).ready(function() {
		var stompClient = null;
		disconnect();
		$("#connect").on("click", function(e) {
			connect();
		})
		$("#disconnect").on("click", function(e) {
			disconnect();
		})
		$("#sendName").on("click", function(e) {
			sendName();
		})

		//设置连接的页面的元素的初始化样式
		function setConnected(connected) {
			$("#connect").attr("disabled", connected);
			$("#disconnect").attr("disabled", !connected);
			$("#conversationDiv").css({
				"visibility" : connected ? 'visible' : 'hidden'
			});
			$("#response").html("");
		}
		//创建连接
		function connect() {
			var socket = new SockJS('/chat');
			stompClient = Stomp.over(socket);
			stompClient.connect({}, function(frame) {
				setConnected(true);
				console.log('Connected: ' + frame);
				stompClient.subscribe('/topic/greetings', function(greeting) {
					showGreeting(JSON.parse(greeting.body).content);
				});
			});
		}
		//断开连接运行的方法
		function disconnect() {
			if (stompClient != null) {
				stompClient.disconnect();
			}
			setConnected(false);
			console.log("Disconnected");
		}

		//发送消息的方法
		function sendName() {
			var name = $('#name').val();
			stompClient.send("/app/chat", {}, JSON.stringify({
				'name' : name
			}));
		}
		function showGreeting(message) {
			var response = $('#response');
			var p = $('p');
			p.css({
				"wordWrap" : "break-word"
			});
			p.html(message)
			//p.appendChild(document.createTextNode(message));
			response.appendTo(p);
		}

	})
</script>
</head>
<body>
	<noscript>
		<h2 style="color: #ff0000">Seems your browser doesn't support
			Javascript! Websocket relies on Javascript being enabled. Please
			enable Javascript and reload this page!</h2>
	</noscript>
	<div>
		<div>
			<button id="connect">Connect</button>
			<button id="disconnect" disabled="disabled">Disconnect</button>
		</div>
		<div id="conversationDiv">
			<label>What is your name?</label><input type="text" id="name" />
			<button id="sendName">Send</button>
			<p id="response"></p>
		</div>
	</div>
</body>
</html>